package com.novel.authorization.tenant;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.novel.base.config.properties.CustomTenantProperties;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * TenantHandler
 *
 * @author 樊温军
 * @date 2025/3/19 下午12:14
 */
@Component
@Slf4j
public class CustomTenantHandler implements TenantLineHandler {

    @Resource
    private CustomTenantProperties customTenantProperties;

    @Override
    public Expression getTenantId() {
        // 从当前系统上下文中取出当前请求的服务商ID，通过解析器注入到SQL中。
        String tenantId = TenantContextHolder.getTenantId();
        log.info("当前租户为{}", tenantId);
        if (tenantId == null) {
            return new NullValue();
        }
        return new StringValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return customTenantProperties.getColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return customTenantProperties.getTables().stream().noneMatch((e) -> e.equalsIgnoreCase(tableName));
    }
}
